<script setup>
import {onMounted, ref} from 'vue';
import {ElMessage} from "element-plus";
import axios from '../request.js';

const username = ref('');
const points = ref();
const buttonText = ref('立即签到');
const checkinDate = ref();

// 用于跟踪是否已签到
const isCheckedIn = ref(false);

const pointsEvents = ref([]);
const showDialog = ref(false)
const pointsNumber = ref()
const balance = ref()
const lotteryItems = ref([]);
const lotteryRecords = ref([]);
const exchangeList = ref();
const earnMethods = ref([
  {title: '签到', description: '登陆并签到可获得积分，每日首次签到可获得50积分。'},
  {title: '上机', description: '通过上机可根据上机时长获得大量的积分奖励。'},
  {title: '购买', description: '在本网咖购买食物可获得相应的积分奖励。'},
  {title: '抽奖', description: '每天可进行抽奖，奖池中可以获得一定的积分。'},
]);

onMounted(() => {
  getPoints();
  getPointsEvents();
  getLotteryItems();
  getExchangeItems();
  getLotteryRecords();
})

const getPoints = () => {
  axios.get("/points/getPoints").then(resp => {
    username.value = resp.message;
    points.value = resp.date[0].points;
    checkinDate.value = resp.date[0].lastCheckinDate;

    // 获取今天的日期
    const date = new Date();
    const formattedToday = formatDate(date);

    // 比较签到日期和今天的日期,并修改签到状态
    if (checkinDate.value === formattedToday) {
      isCheckedIn.value = true; // 更新签到状态
      buttonText.value = '已签到'; // 更新按钮文本
    }
  })
};

//转换date为yyyy-MM-dd格式
const formatDate = (dateString) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

//签到
const clickPoints = () => {
  axios.put("/points/dailyCheckIn", null, {
    params: {
      username: username.value,
    }
  }).then(resp => {
    if (resp === true) {
      ElMessage.success("签到成功");
      isCheckedIn.value = true; // 更新签到状态
      buttonText.value = '已签到'; // 更新按钮文本
      getPoints();
      getPointsEvents();
    } else if (resp === 'false1') {
      ElMessage.error("当天已签到，请明天再签");
      isCheckedIn.value = true; // 更新签到状态
      buttonText.value = '已签到'; // 更新按钮文本
    }
  })
}

//获取抽奖列表
const getLotteryItems = () => {
  axios.get("/points/getLotteryItems").then(resp => {
    lotteryItems.value = resp.date;
  })
}

//点击抽奖
const clickLottery = () => {
  axios.get("/points/lotteryDraw", {
    params: {
      pointsValue: 500,
    }
  }).then(resp => {
    if (resp === "抽奖次数已用完") {
      ElMessage.error("抽奖次数已用完,请明天再试");
    } else if (resp === "积分不足") {
      ElMessage.error("积分不足");
    } else {
      const randomNumber = getRandomCode();
      lotteryItems.value.forEach(item => {
        if (item.lotteryItemsId === resp) {
          if (item.type === 0 || item.type === 1) {
            alert("恭喜你抽中了：" + item.title)
            getPoints();
            getPointsEvents();
            getLotteryRecords();
          }
          if (item.type === 2) {
            alert("恭喜你抽中了：" + item.title + ",这是你的兑换码：" + `${randomNumber}`)
            getPoints();
            getPointsEvents();
            getLotteryRecords();
          }
        }
      })
    }
  })
};

//获取抽奖历史
const getLotteryRecords = () => {
  axios.get("/points/getLotteryRecords").then(resp => {
    lotteryRecords.value = resp.date;
  })
};

//积分兑换余额
const exchangePoints = () => {
  if (pointsNumber.value === undefined) {
    ElMessage({
      message: '请输入兑换积分',
      showClose: true,
      grouping: false,
      type: 'warning',
    })
    return;
  }

  if (!/^[0-9]*$/.test(pointsNumber.value) && !/^(0|([1-9][0-9]*))(\.[\d]+)?$/.test(pointsNumber.value) || pointsNumber.value == 0) {
    ElMessage({
      message: '请输入正确的积分',
      showClose: true,
      grouping: false,
      type: 'error',
    })
    return;
  }

  if (pointsNumber.value > points.value) {
    ElMessage({
      message: '积分不足，请先获取积分',
      showClose: true,
      grouping: false,
      type: 'warning',
    })
    return;
  }

  balance.value = pointsNumber.value / 1000;

  showDialog.value = true
};

//积分兑换余额,取消
const exchangePointsNo = () => {
  showDialog.value = false
};
//积分兑换余额,确认
const exchangePointsYes = () => {
  axios.get("/points/pointsToBalance", {
    params: {
      pointsNumber: pointsNumber.value,
      balance: balance.value,
    }
  }).then(resp => {
    if (resp === true) {
      ElMessage.success("兑换成功");
      getPoints();
    } else if (resp === false) {
      ElMessage.error("积分不足，请先获取积分");
    } else if (resp === "false1") {
      ElMessage.error("兑换失败");
    }
  })
  showDialog.value = false
}

//获取积分兑换商品列表
const getExchangeItems = () => {
  axios.get("/points/getExchangeItems").then(resp => {
    exchangeList.value = resp.date;
  })
}

//积分换商品,显示对话框
const exchangeItems = (index) => {
  exchangeList.value[index].showDialog = true;
};

//积分换商品,取消兑换
const exchangeItemsNo = (index) => {
  exchangeList.value[index].showDialog = false;
};

// 生成一个随机数，取值范围为100000到999999
const getRandomCode = () => {
  const min = 100000;
  const max = 999999;
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

//积分换商品,确认兑换
const exchangeItemsYes = (index) => {
  exchangeList.value[index].showDialog = false;

  if (points.value >= exchangeList.value[index].price) {
    if (exchangeList.value[index].type === '0') {
      axios.get("/points/exchangeItemsType0", {
        params: {
          couponsId: exchangeList.value[index].exchangeItemsId,
          pointsNumber: exchangeList.value[index].price,
        }
      }).then(resp => {
        if (resp === true) {
          ElMessage.success("兑换成功");
          getPoints();
        } else if (resp === false) {
          ElMessage.error("积分不足，请先获取积分");
        } else if (resp === "false1") {
          ElMessage.error("该商品已兑换过,需要先使用才能再次兑换");
        } else if (resp === "false2") {
          ElMessage.error("兑换失败");
        }
      })
    } else if (exchangeList.value[index].type === '1') {
      //随机兑换码
      const randomCode = getRandomCode();
      axios.get("/points/exchangeItemsType1", {
        params: {
          pointsNumber: exchangeList.value[index].price,
        }
      }).then(resp => {
        if (resp === true) {
          alert(`请到自助机或者前台兑换,您的兑换码是：${randomCode}`)
          getPoints();
        } else if (resp === false) {
          ElMessage.error("积分不足，请先获取积分");
        } else if (resp === "false1") {
          ElMessage.error("兑换失败");
        }
      })
    } else if (exchangeList.value[index].id === 1 || exchangeList.value[index].id === 2) {
      axios.get("/points/exchangeItemsCoupons", {
        params: {
          couponsId: exchangeList.value[index].id,
          pointsNumber: exchangeList.value[index].price,
        }
      }).then(resp => {
        if (resp === true) {
          ElMessage.success("兑换成功");
          getPoints();
        } else if (resp === "false1") {
          ElMessage.error("该优惠券已拥有");
        } else if (resp === "false2") {
          ElMessage.error("兑换失败");
        } else if (resp === "false3") {
          ElMessage.error("积分不足，请先获取积分");
        }
      })
    }
  } else {
    ElMessage.error("积分不足，请先获取积分");
  }

};

//获取积分出入事件
const getPointsEvents = () => {
  axios.get("/points/getPointsEvent").then(resp => {
    pointsEvents.value = resp;
  })
};
</script>

<template>
  <div class="return">
    <router-link to="/index" class="return-router-link">返回首页</router-link>
    <router-link to="/RechargeCard" class="return-router-link">返回充值页</router-link>
  </div>
  <div class="container">

    <div class="header">
      <h1>网咖个人积分中心</h1>
      <p>尊敬的{{ username }}用户，您本月还剩{{ points }}积分可使用</p>
    </div>

    <div class="body1">

      <div class="click-points">
        <div class="points">{{ points }}</div>
        <span>每天签到可免费获取50积分</span>
        <button @click="clickPoints" :disabled="isCheckedIn">{{ buttonText }}</button>
      </div>

      <div class="points-info">
        <h2>积分系统说明</h2>
        <p>积分可兑换相应的优惠券、账户余额等；积分可累积，积分每月月底清零。</p>
        <p>1. 用户可以通过签到、上机、购买商品等方式获取积分。</p>
        <p>2. 积分兑换后立即生效，兑换后的产品不可退换。</p>
        <p>3. 每月兑换累计最多50000积分。</p>
      </div>

    </div>

    <div class="body2">

      <h2>积分抽奖</h2>

      <div class="lottery-body">

        <div class="lottery-left">

          <div class="lottery-prize">
            <div class="lottery-list" v-for="(item, index) in lotteryItems" :key="index">
              <span>{{ item.title }}</span><br>
              <span v-if="item.number===0">奖品已被抽完</span>
            </div>
            <div class="click-lottery" @click="clickLottery">
              <span>抽奖 - 500积分</span>
            </div>
          </div>

          <div class="lottery-info">
            <span>当前积分: {{ points }}, 每次抽奖扣500积分</span>
          </div>

        </div>

        <div class="lottery-right">
          <h3>获奖区</h3>
          <div class="lottery-record" v-for="(item, index) in lotteryRecords" :key="index">
            <span>{{item.username }} 抽奖，获得了{{ item.lotteryItemsTitle }} 。日期：{{ item.date }}</span>
          </div>
        </div>

      </div>

    </div>

    <div class="body3">

      <h2>积分兑换区</h2>

      <div class="exchange-body">

        <div class="exchange-list">
          <h3>积分换余额</h3>
          <input type="text" v-model="pointsNumber" placeholder="输入积分"/>
          <p>积分余额兑换比例: 1000:1</p>
          <el-button plain @click="exchangePoints">立即兑换</el-button>
          <el-dialog v-model="showDialog" title="提示" width="500" center draggable overflow>
            <span>{{ pointsNumber }} 积分可以兑换余额 {{ balance }} 元, 是否要兑换？</span>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="exchangePointsNo">取消</el-button>
                <el-button @click="exchangePointsYes">确定</el-button>
              </div>
            </template>
          </el-dialog>
        </div>

        <div class="exchange-list" v-for="(item, index) in exchangeList" :key="index">
          <h3>{{ item.title }}</h3>
          <p>{{ item.description }}</p>
          <p>{{ item.price }}</p>
          <el-button plain @click="exchangeItems(index)">立即兑换</el-button>
          <el-dialog v-model="item.showDialog" title="提示" width="500" center draggable overflow>
            <span>{{ item.description }}</span>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="exchangeItemsNo(index)">取消</el-button>
                <el-button type="primary" @click="exchangeItemsYes(index)">确定</el-button>
              </div>
            </template>
          </el-dialog>
        </div>
      </div>

    </div>

    <div class="body4">

      <div class="points-detail">
        <h2>积分出入明细</h2>
        <ul>
          <el-scrollbar height="400px">
            <li v-for="(list, index) in pointsEvents" :key="index">
              <span>{{ list.eventTime }}</span>
              <span>{{ list.event }}</span>
              <span>{{ list.points }}</span>
            </li>
          </el-scrollbar>

        </ul>
      </div>

      <div class="points-way">
        <h2>积分获得途径</h2>
        <div class="points-way-list" v-for="(method, index) in earnMethods" :key="index">
          <h3>{{ method.title }}</h3>
          <p>{{ method.description }}</p>
        </div>
      </div>

    </div>

  </div>
  <div class="return">
    <router-link to="/index" class="return-router-link">返回首页</router-link>
    <router-link to="/RechargeCard" class="return-router-link">返回充值页</router-link>
  </div>
</template>


<style scoped>
.return {
  text-align: center;
  margin: 10px 0 0 0;
  font-size: 18px;
}

.return-router-link{
  text-decoration: none;
  margin: 0 40px 0 40px ;
  color: black;
}

.return-router-link:hover{
  color: #f53e3e;
}

.container {
  max-width: 1150px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  text-align: center;
  background-color: #e8cf6b;
  padding: 20px;
  border-radius: 10px;
  margin-bottom: 20px;
}

.header h1 {
  font-size: 24px;
  margin: 0;
  color: #fff;
}

.header p {
  font-size: 16px;
  margin: 5px 0 0 0;
  color: #fff;
}

.body1 {
  display: flex;
  margin-bottom: 20px;
}

.click-points {
  background-color: #fff3cd;
  border: 1px solid #ffc107;
  padding: 20px;
  border-radius: 10px;
  text-align: center;
  width: 220px;
  margin-right: 10px;
}

.click-points .points {
  font-size: 36px;
  margin-bottom: 10px;
  color: #ff6600;
}

.click-points button {
  background-color: #ff6600;
  color: #fff;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  margin-top: 10px;
}

.points-info {
  background-color: #fff3cd;
  border: 1px solid #ffc107;
  padding: 20px;
  border-radius: 10px;
  flex: 1;
}

.points-info h2 {
  font-size: 18px;
  margin-bottom: 10px;
}

.points-info p {
  margin: 5px 0;
}

.body2 {
  border: 1px solid #ffcc00;
  border-radius: 10px;
  margin-bottom: 20px;
  text-align: center;
}

.body2 h2 {
  font-size: 18px;
  margin-bottom: 10px;
}

.lottery-body {
  display: flex;
  padding: 20px;
  background-color: #fff3cd;
  border: 1px solid #ffc107;
  border-radius: 10px;
  position: relative;
}

.lottery-left {
  margin: 0 60px 0 60px;
}

.lottery-prize {
  width: 450px;
  height: 450px;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  border-radius: 10px;
}

.lottery-list {
  background-color: #fff;
  border: 1px solid #ffc107;
  padding: 20px;
  border-radius: 10px;
}

.lottery-list span {
  color: red;
}

.click-lottery {
  margin: auto;
  grid-column: 2;
  grid-row: 2;
  background-color: #ff6600;
  color: #fff;
  padding: 20px;
  border-radius: 50%;
  cursor: pointer;
}

.lottery-info {
  width: 340px;
  margin: 10px 0 0 40px;
}

.lottery-info span {
  font-size: 20px;
  color: #ff6600;
}

.lottery-right {
  width: 480px;
  height: 450px;
  margin: 0;
  border: 1px solid #ff0090;
  border-radius: 5px;
  overflow: auto;
}

.lottery-record {
  margin-bottom: 5px;
}

.body3 {
  text-align: center;
  border: 1px solid #ffcc00;
  border-radius: 10px;
  margin-bottom: 20px;
}

.body3 h2 {
  font-size: 18px;
  margin-bottom: 10px;
}

.exchange-body {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.exchange-list {
  background-color: #fff3cd;
  border: 1px solid #ffc107;
  padding: 20px;
  margin: 10px;
  border-radius: 10px;
  text-align: center;
  flex: 0 0 30%;
  box-sizing: border-box;
}

.exchange-list h3 {
  font-size: 16px;
  margin-bottom: 10px;
}

.exchange-list input {
  height: 20px;
  width: 150px;
}

.exchange-list p {
  margin-bottom: 10px;
}

.exchange-list button {
  background-color: #ff6600;
  color: #fff;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
}

.body4 {
  display: flex;
  margin-bottom: 20px;
}

.points-detail {
  width: 45%;
  background-color: #fff;
  border: 1px solid #ffcc00;
  padding: 20px;
  border-radius: 10px;
  margin-right: 10px;
}

.points-detail h2 {
  text-align: center;
  font-size: 18px;
  margin-bottom: 10px;
  background-color: #ffcc00;
  padding: 5px;
  color: #fff;
  border-radius: 5px;
}

.points-detail ul {
  padding: 0;
  margin: 0;
}

.points-detail li {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  margin-bottom: 5px;
  background-color: #fff3cd;
  border: 1px solid #ffc107;
  border-radius: 5px;
}

.points-way {
  width: 45%;
  background-color: #fff;
  border: 1px solid #ffcc00;
  padding: 20px;
  border-radius: 10px;
}

.points-way h2 {
  text-align: center;
  font-size: 18px;
  margin-bottom: 10px;
  background-color: #ffcc00;
  padding: 5px;
  color: #fff;
  border-radius: 5px;
}

.points-way-list {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #fff3cd;
  border: 1px solid #ffc107;
  border-radius: 5px;
}

.points-way-list h3 {
  font-size: 16px;
  margin-bottom: 5px;
}

.points-way-list p {
  margin: 0;
}
</style>
